//
//  ViewController.m
//  MouseShaker
//
//  Created by LiuLichen on 2022/5/7.
//

#import "ViewController.h"

#import <AppKit/AppKit.h>

#import "SBPopoverViewController.h"

@interface ViewController()

@property (nonatomic, strong) NSStatusItem* statusItem;
@property (nonatomic, strong) NSPopover* popover;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Create StatusItem on the status bar
    self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength: NSVariableStatusItemLength];
    NSImage* statusImage = [NSImage imageNamed: @"StatusItem"];
    [self.statusItem.button setImage: statusImage];

    // Create popover view for the status item
    self.popover = [[NSPopover alloc] init];
    self.popover.behavior = NSPopoverBehaviorTransient;
    self.popover.appearance = [NSAppearance appearanceNamed: NSAppearanceNameVibrantLight];
    self.popover.contentViewController = [[SBPopoverViewController alloc] initWithNibName:@"SBPopoverViewController" bundle:nil];
    SBPopoverViewController* sbPop = (SBPopoverViewController*)self.popover.contentViewController;

    // Add click event for status item
    self.statusItem.button.target = self;
    self.statusItem.button.action = @selector(showPopover:);

    // Add mouse click event listener
    __weak typeof(self) weakSelf = self;
    [NSEvent addGlobalMonitorForEventsMatchingMask:NSEventMaskLeftMouseDown | NSEventMaskMouseMoved handler:^(NSEvent* event) {
        switch (event.type) {
            case NSEventTypeLeftMouseDown:
                if (weakSelf.popover.isShown) {
                    [weakSelf.popover close];
                }
                break;
            case NSEventTypeMouseMoved:
                [sbPop notifyMouseMoved];
                break;
            default:
                break;
        }
    }];
}

- (SBPopoverViewController*)getSBPopoverViewController {
    return (SBPopoverViewController*)self.popover.contentViewController;
}


- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}

- (void) showPopover:(NSStatusBarButton*)button {
    [self.popover showRelativeToRect:button.bounds ofView:button preferredEdge:NSRectEdgeMaxY];
}

@end
